package org.xu.controller;

import com.core.base.Reply;
import com.core.utils.HttpFormUtil;
import com.core.utils.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xu.entity.WorkFlowLogEntity;
import org.xu.enums.WorkTypeEnum;
import org.xu.logic.*;
import org.xu.service.WorkFlowLogService;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/api/test/")
@RestController
public class SignInController {

    @Autowired
    private WorkFlowLogService workFlowLogService;
    @Autowired
    @Qualifier("IOTaskExecutorPool")
    private Executor executor;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SignLogic signLogic;
    @Autowired
    private WeChatTaskLogic weChatTaskLogic;
    @Autowired
    private QuestionLogic questionLogic;
    @Autowired
    private AwardLogic awardLogic;
    @Autowired
    private FeedAlmondLogic feedAlmondLogic;

    private static final String dataId = "017db6b6cc478a7e88867db6signIn";
    private static final String dataIdStr = "signIn";

    @RequestMapping("/feedAlmond")
    public Reply<String> feedAlmond(){
        List<String> tokenList = getTokenMap().values().stream().distinct().collect(Collectors.toList());
        for (int i = 0; i < tokenList.size(); i++) {
            feedAlmondLogic.feedAlmond("test_feedAlmond_"+ i,tokenList.get(i));
        }
        return Reply.success("award");
    }

    @RequestMapping("/award")
    public Reply<String> award(){
        List<String> tokenList = getTokenMap().values().stream().distinct().collect(Collectors.toList());
        for (int i = 0; i < tokenList.size(); i++) {
            awardLogic.award("test_award_"+ i,tokenList.get(i));
        }
        return Reply.success("award");
    }

    @RequestMapping("/food/sign")
    public Reply<String> getFood(){
        List<String> tokenList = getTokenMap().values().stream().distinct().collect(Collectors.toList());
        for (int i = 0; i < tokenList.size(); i++) {
            signLogic.acquireFood("test_food_"+ i,tokenList.get(i));
        }
        return Reply.success("Food");
    }

    @RequestMapping("/questionCommit")
    public Reply<String> questionCommit() {
        List<String> tokenList = getTokenMap().values().stream().distinct().collect(Collectors.toList());
        for (int i = 0; i < tokenList.size(); i++) {
            questionLogic.questionCommit("test_questionCommit_"+ i,tokenList.get(i));
        }
        return Reply.success("questionCommit");
    }

    @RequestMapping("/video/finish")
    public Reply<String> videoFinish() {
        List<String> tokenList = getTokenMap().values().stream().distinct().collect(Collectors.toList());
        for (int i = 0; i < tokenList.size(); i++) {
            weChatTaskLogic.videoFinish(""+ i,tokenList.get(i));
        }
        return Reply.success("Food");
    }

    @RequestMapping("/force/execute")
    public Reply<String> forceExecute() {
        execute();
        return Reply.success("6666666");
    }

    // 预期 10 、 15 、 20 各执行一次
    @RequestMapping("/signIn")
    public Reply<String> signIn(){
        if (LocalDateTime.now().getHour() <= 9){
            // 9 点之前不执行
            return Reply.success("6");
        }
        boolean exist = Boolean.TRUE.equals(redisTemplate.hasKey(dataId));
        if (exist) {
            return Reply.success("6");
        }
        redisTemplate.opsForValue().set(dataId, LocalDateTime.now().toString());
        try {
            redisTemplate.expire(dataId, 9, TimeUnit.HOURS);
            LocalDateTime now = LocalDateTime.now();
            int year = now.getYear();
            if (year > 2024){
                return Reply.success(String.valueOf(year));
            }
        }catch (Exception ignored){
        }
        execute();
        return Reply.success("6");
    }

    private void execute(){
        executor.execute(() ->{
            LocalDate oldLocalDate = LocalDate.now().minusDays(2);
            workFlowLogService.deleteHistoryData(oldLocalDate);
            Map<String,String> tokenMap = getTokenMap();
            log.info("token:Size:{}",tokenMap.keySet().size());
            Set<Map.Entry<String, String>> entries = tokenMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String name = entry.getKey();
                String token = entry.getValue();
                // 首页登录签到
                send(name,token);
                // 转盘
                awardLogic.award(name,token);
                // 机器登录
                signLogic.acquireFood(name,token);
                // 答题
                questionLogic.questionCommit(name,token);
                // 视频
                weChatTaskLogic.videoFinish(name,token);
                // 机器人 喂养 结果
                feedAlmondLogic.feedAlmond(name + "_喂养",token);
            }
        });
    }

    public void send(String key,String token) {
        StringBuffer sbf = new StringBuffer();
        sbf.append("------WebKitFormBoundaryQ0rzq3BR5c3dQgNN\r\n")
                .append("Content-Disposition: form-data; name=\"token\"\r\n")
                .append("\r\n")
                .append(token.trim())
                .append("\r\n------WebKitFormBoundaryQ0rzq3BR5c3dQgNN--");
        String urlString = "https://h5up.bluebirdh5.top/sq/YxDecennial/signIn";
        String timesResponse = HttpFormUtil.formCommit("首页登录签到",urlString, sbf.toString(), "----WebKitFormBoundaryQ0rzq3BR5c3dQgNN");
        if (!"失败".equals(timesResponse)) {
            // 构建表单数据
            WorkFlowLogEntity entity = new WorkFlowLogEntity();
            entity.setId(UUIDGenerator.generate());
            entity.setDataId(dataIdStr);
            entity.setApplyNo("test_"+key);
            entity.setWorkType(WorkTypeEnum.SIGN);
            entity.setCreateTime(new Date());
            entity.setOperationResult(key + ":首页登录签到完成");
            entity.setRemark(timesResponse);
            entity.setDeleted(false);
            workFlowLogService.insert(entity);
        }
    }

    private Map<String,String> getTokenMap(){
        LinkedHashMap<String, String> nameTokenMap = new LinkedHashMap<>();
        nameTokenMap.put("瑞","ArDyrrLAddotiXNeGMeDKE4Ctg3gfiid4RA0SYQ4KLwgxQ");
        nameTokenMap.put("002","DuGuqbfCdN4tiXNeGMeDZw5FuVfmfiid4h4yRYg4KLwkxQ");
        nameTokenMap.put("Z鹏","X7P9rbvGct0tiXNeGMeDYAJauAThfiid5xs/S4k4KLwr");
        nameTokenMap.put("001","C7z7/OfPfYwtiXNeGMeDYAMFuk+nfiid5RowRYV9ZfFvwHg");
        nameTokenMap.put("廖","Cbfzo+aUJYItiXNeGMeDaQ1RvQfjfiid5RowRYlxZfFvzA");
        nameTokenMap.put("6666","W7SqrLbHJYgtiXNeGMeDNVJW60fgfiid5Rk+RIJ0ZfFvzXE");
        nameTokenMap.put("7777","D735o+bPdogtiXNeGMeDPwsAvUy0fiid5RE0S4h9ZfFvwXc");
        List<WorkFlowLogEntity> list = workFlowLogService.listByDataId(dataId);
        if (!CollectionUtils.isEmpty(list)){
            for (int i = 0; i < list.size(); i++) {
                WorkFlowLogEntity entity = list.get(i);
                if (StringUtils.isEmpty(entity.getRemark())){
                    continue;
                }
                String name = StringUtils.isEmpty(entity.getApplyNo()) ? String.valueOf(i) : entity.getApplyNo();
                nameTokenMap.put(name,entity.getRemark().trim());
            }
        }
        return nameTokenMap;
    }


        public static void main(String[] args) {
            LocalDateTime now = LocalDateTime.now();
            int year = now.getYear();
            System.out.println(year);

        }

}
